// exam begin
(function() {
	var _saveCalledNum = 0;
	var _paperMode = 'full'; // full/single（答卷模式：整版/单题）
	var _isSaving = false; // 用来标记是否正在保存，防止方法调用/重入
	var _lastSavedTime = 0; // 最近1次保存完成（无论成功/失败）时间
	function _isPaperModeFull() {
		return _paperMode == 'full';
	}

	function _isPaperModeSingle() {
		return _paperMode == 'single';
	}

	function _setPaperModeFull() {
		_paperMode = 'full';
		$("*[basicType],.whiteblank").show();
		$(".section").show();
	}

	function _setPaperModeSingle() {
		_paperMode = 'single';
		$("*[basicType],.whiteblank").hide();
		_jumpTo(null);
	}

	function _jumpTo(i) { // 点击序号跳转至试题, start from 0
		if (i == null && jsExampro.totalQuestionNum <= 0)
			return;
		if (i == null) {
			if (jsExampro.currentQuestionIndex < 0) {
				jsExampro.currentQuestionIndex = 0;
			}
			i = jsExampro.currentQuestionIndex;
		} else if (jsExampro.currentQuestionIndex == i) {
			return;
		}

		// 旧的current
		$("#question" + jsExampro.currentQuestionIndex).removeClass("current");
		if (_isPaperModeSingle()) {
			$("#question" + jsExampro.currentQuestionIndex).hide();
			$("#question" + jsExampro.currentQuestionIndex).parents("[basicType]").hide();
		}
		// 旧的current的parent
		var parentId = $("#question" + jsExampro.currentQuestionIndex).attr("parentId");
		if (parentId != null) {
			$(".complex[questionId=" + parentId + "]").removeClass("complexCurrent");
		}

		jsExampro.currentQuestionIndex = i;

		// 新的current
		$("#question" + jsExampro.currentQuestionIndex).addClass("current");
		if (_isPaperModeSingle()) {
			$("#question" + jsExampro.currentQuestionIndex).show();
			$("#question" + jsExampro.currentQuestionIndex).parents().show();
		}
		// 新的current的parent
		parentId = $("#question" + jsExampro.currentQuestionIndex).attr("parentId");
		if (parentId != null) {
			$(".complex[questionId=" + parentId + "]").addClass("complexCurrent");
		}

		if (_isPaperModeFull()) {
			//$("input[sn=" + jsExampro.currentQuestionIndex + "]").focus().blur();
			var loc = "#question" + jsExampro.currentQuestionIndex;
			var elemTop = $(loc).position().top; // 相对于父元素的位置
			//console.log(">elemTop>" + elemTop + ">>>" + $("#mainpanel").scrollTop());
			//console.log($("#mainpanel").height());
			var tmp = elemTop - $(window).scrollTop();
			var winHeight = $("#msgboxReshow").position().top - $(window).scrollTop();
			if (tmp < 0 || tmp > winHeight) {
				//var offset = elemTop - $("#mainpanel").position().top - $("#mainpanel").height();
				//$("#mainpanel").scrollTop($(loc).position().top);
				//elemTop = $("*[questionIndex=" + jsExampro.currentQuestionIndex + "]").position().top; // 相对于父元素的位置
				//$("#mainpanel").animate({"scrollTop": elemTop + 20}, 10);
				window.location.href = loc;
				$(window).scrollTop($(window).scrollTop() - 90);
			}
		} else { // 显示所属大题信息
			$("tr.section").hide();
			if ($("#question" + jsExampro.currentQuestionIndex).parents(".complex").size() > 0) {
				$("#question" + jsExampro.currentQuestionIndex).parents(".complex").prevAll("tr.section:first").show();
			} else {
				$("#question" + jsExampro.currentQuestionIndex).prevAll("tr.section:first").show();
			}

			var isSingleTime = $("#isSingleTime[value='1']").size() > 0;
			if (isSingleTime)
				$("#singleTimeBar").html("&nbsp;").css("width", "0px"); // 单题计时
		}
	}

	function _jumpToPrev() { // 上一题
		if (jsExampro.currentQuestionIndex > 0) {
			_jumpTo(jsExampro.currentQuestionIndex - 1);
			return;
		}
		_jumpTo(0);
	}

	function _jumpToNext() { // 下一题
		if (jsExampro.currentQuestionIndex < jsExampro.totalQuestionNum - 1) {
			_jumpTo(jsExampro.currentQuestionIndex + 1);
		}
	}

	function _startSaveTimer() {
		jsExampro.replySaveTimer = setInterval("jsExampro.replySave()", 29789); // 半分钟
	}

	function _prepareForSave() {
		$("#paperForm").find(".userAnswer[changed]").attr("changed", "saving");
		var replies = [];
		var isSingleTime = $("#isSingleTime[value='1']").size() > 0;
		$("#paperForm").find(".userAnswer[changed='saving']").each(function(i, item) {
			if ($(item).is(":radio") && !$(item).is(":checked"))
				return;
			var obj = {};
			obj.r = $(item).val();
			obj.q = $(item).attr("name").substring(1);
			if (isSingleTime) {
				obj.t = $(item).parents(".question").attr("answerMs");
			}
			replies.push(obj);
		});
		$("#saveForm input[name='replyNum']").val(replies.length);
		$("#saveForm .data").val(JSON.stringify({
			"replies": replies,
			"replyPercent": _getRepliedPercent()
		}));
		return replies.length;
	}

	// 定时自动保存
	function _replySave(manual) {
		if (_lastSavedTime == 0)
			_lastSavedTime = (new Date()).getTime();
		var uuid = (new Date()).getTime();
		var isManual = typeof(manual) == 'undefined' ? false : true; // 手工点击/自动保存
		if (isManual) {
			jsMsgbox.show();
		}
		if (_isSaving) { // 防止方法调用重入
			var now = (new Date()).getTime();
			if (now - _lastSavedTime < 60000) {
				jsMsgbox.addMsg("上一保存进行中...", uuid + (isManual ? "[m]" : "[a]"), 'warn');
				return;
			}
		}
		_saveCalledNum++;
		var changedNum = _prepareForSave();
		var changed = changedNum > 0;
		if (!changed && (_saveCalledNum % 6) != 0 && !isManual)
			return; // noChanged and notHeartbeat and notManual

		_isSaving = true; // 正在保存
		jsMsgbox.addMsg("正在保存...", uuid + (isManual ? "[m]" : "[a]"));
		$.ajax({
			dataType: "json",
			cache: false,
			type: 'POST',
			timeout: 10000, // timeout 10秒 够慢的了
			async: true,
			url: jsExampro.basePath + jsExampro.urlAjaxSave,
			beforeSend: function(XMLHttpRequest) {},
			data: $("#saveForm").serialize(),
			success: function(data, textStatus) {
				if (typeof(data.err) == 'undefined') {
					jsMsgbox.addMsg("保存失败[unknown]", uuid + (isManual ? "[m]" : "[a]"), 'error');
					jsMsgbox.show();
					return;
				} else if (data.err == 1) {
					jsMsgbox.addMsg("保存失败[" + data.msg + "]", uuid + (isManual ? "[m]" : "[a]"), 'error');
					jsMsgbox.show();
					if (data.submitted == 1) {
						jsBlockbox.blockbox("收到强制交卷指令！", "<input type='button' id='btnSubmitNow' value='立即交卷' onclick='doSubmit()' />", jsBlockbox.VERYHIGH);
					}
					return;
				}
				jsExampro.lastLeftSeconds = jsExampro.leftSeconds = data.leftSeconds;
				jsExampro.lastClientNow = (new Date()).getTime();
				$("#paperForm").find(".userAnswer[changed='saving']").each(function(i, item) {
					var tmpidx = $(item).parents(".question").attr("questionIndex");
					var tmpreplied = _isReplied(tmpidx);
					if (tmpreplied) {
						$("#jmp" + tmpidx).addClass("saved");
					} else {
						$("#jmp" + tmpidx).removeClass("replied").removeClass("saved");
					}
				});
				$("#paperForm").find(".userAnswer[changed='saving']").removeAttr("changed");
				var strmsg = "保存成功";
				if (typeof(data.msg) != 'undefined') {
					strmsg += "[" + data.msg + "]";
				}
				jsMsgbox.addMsg(strmsg, uuid + (isManual ? "[m]" : "[a]"));
				if (data.delayMinutes != $("input[name='delayMinutes']").val()) {
					jsMsgbox.addMsg("考试延时变化，累计延时" + data.delayMinutes + "分钟", "", "important");
					jsMsgbox.show();
					$("input[name='delayMinutes']").val(data.delayMinutes);
				}
				if (data.suspendReply != $("input[name='suspendReply']").val()) {
					$("input[name='suspendReply']").val(data.suspendReply);
					_suspendReply();
					_resumeReply();
				}
				if (data.forceGetPaper == 1) {
					_forceGetPaper();
				}
				$("input[name='mouseOut']").val(0); // 交互1次后即恢复状态
			},
			complete: function(xhr, textStatus) {
				_isSaving = false;
				_lastSavedTime = (new Date()).getTime();
			},
			error: function(xhr, textStatus, errorThrown) {
				jsMsgbox.addMsg("保存失败[" + textStatus + "]", uuid + (isManual ? "[m]" : "[a]"), 'error');
				jsMsgbox.addMsg(xhr.responseText, uuid + (isManual ? "[m]" : "[a]"), 'detail');
				jsMsgbox.show();
				//_debugNetwork();
			}
		});
	}

	function _debugNetwork() {
		var img = jsExampro.basePath + "web/images/exampro/smile.png?r=" + Math.random() + "&d=" + (new Date()).getTime();
		jsMsgbox.addMsg("网络连通诊断中...<img src='" + img + "' border='0' />");
		jsMsgbox.addMsg("如果看不到上面的笑脸，说明您已断网，请联系网络管理员协助", "", 'important');
		jsMsgbox.show();
	}

	function _forceGetPaper() {
		jsMsgbox.addMsg("收到系统强制收卷指令，本次考试即将结束", "", "important");
		jsMsgbox.show();
		jsBlockbox.msg("收到系统强制收卷指令，本次考试即将结束");
		setTimeout("jsExampro.clearLeftSeconds()", 2500); // 给出一定延时，让考生看清提示信息
	}

	var _suspendTimer = 0;

	function _suspendReply() {
		if ($("input[name='suspendReply']").val() == "1") {
			jsBlockbox.msg("考试被暂停");
			jsMsgbox.addMsg("考试被暂停", "", "important");
			jsMsgbox.show();
			if (_suspendTimer != 0)
				clearInterval(_suspendTimer);
			_suspendTimer = setInterval("jsExampro.replySave(1)", 4789); // 5秒左右
		}
	}

	function _resumeReply() {
		if ($("input[name='suspendReply']").val() == "0") {
			jsBlockbox.alert("考试暂停解除，请继续作答");
			jsMsgbox.addMsg("考试暂停解除，请继续作答", "", "important");
			jsMsgbox.show();
			if (_suspendTimer != 0)
				clearInterval(_suspendTimer);
			_suspendTimer = 0;
			if (typeof(jsExamBoundary) != 'undefined') {
				jsExamBoundary.start();
			}
		}
	}

	function _countdown() { // 倒计时
		if (jsExampro.leftSeconds == 999999999) return;
		if (jsExampro.leftSeconds <= 0)
			jsExampro.leftSeconds = 0;
		var fmt = _formatSeconds(jsExampro.leftSeconds);
		if (jsExampro.leftSeconds == 600 || jsExampro.leftSeconds == 300 || jsExampro.leftSeconds == 60) {
			jsBlockbox.alert("提示：距离考试结束还有" + Math.round(jsExampro.leftSeconds / 60) + "分钟", jsBlockbox.LOW);
		} else if (jsExampro.leftSeconds == 0) {
			clearInterval(jsExampro.countdownTimer);
			jsExampro.countdownTimer = null;
			clearInterval(jsExampro.replySaveTimer);
			jsExampro.replySaveTimer = null;
			jsBlockbox.blockbox("时间到！", "<input type='button' id='btnSubmitNow' value='立即交卷' onclick='btnSubmit()' />", jsBlockbox.VERYHIGH);
			setTimeout("jsExampro.autoSubmit(5)", 5000);
		}
		$(".countdownHH").html(fmt.charAt(0) + fmt.charAt(1));
		$(".countdownMM").html(fmt.charAt(2) + fmt.charAt(3));
		$(".countdownSS").html(fmt.charAt(4) + fmt.charAt(5));
		jsExampro.leftSeconds--;
		var elapsedSeconds = Math.round(((new Date()).getTime() - jsExampro.lastClientNow) / 1000);
		jsExampro.leftSeconds = Math.min(jsExampro.lastLeftSeconds - elapsedSeconds, jsExampro.leftSeconds); // 双重校正
	}

	function _autoSubmit(n) {
		if (n <= 0) n = 0;
		$("#btnSubmitNow").val("立即交卷（" + n + "秒后自动交卷）");
		if (n == 0) {
			if ($("#btnSubmitNow").size() > 0)
				btnSubmit();
		} else {
			setTimeout("jsExampro.autoSubmit(" + (--n) + ")", 1000);
		}
	}

	function _formatSeconds(seconds) { // 格式化“秒”数为HHMMSS
		var h = Math.floor(seconds / 3600);
		var m = Math.floor((seconds - h * 3600) / 60);
		var s = seconds % 60;
		h = h < 10 ? "0" + h : h;
		m = m < 10 ? "0" + m : m;
		s = s < 10 ? "0" + s : s;
		return h + "" + m + "" + s;
	}

	function _isReplied(questionIndex) {
		var loc = "#question" + questionIndex;
		var basicType = $(loc).attr("basicType");
		var replied = false;
		if (basicType == 1 || basicType == 3) {
			replied = $(loc).find("input:radio:checked").filter(".userAnswer").size() > 0;
		} else if (basicType == 2 || basicType == 10) {
			replied = $(loc).find("input:checkbox:checked").filter(".choice").size() > 0;
		} else if (basicType == 4) {
			$(loc).find("input.blank").each(function(i, item) {
				if ($.trim($(item).val()) != '')
					replied = true;
			});
		} else if (basicType == 5) {
			replied = $.trim($(loc).find(".userAnswer").val()).length > 0;
		} else if (basicType == 6) {
			replied = $.trim($(loc).find(".userAnswer").val()).length > 0;
		}
		return replied;
	}

	function _changeChoiceColor(selector) {
		selector.find(".choice").each(function(i, item) {
			if ($(item).is(":checked")) {
				$(item).nextAll('.cTitle:first,.choiceSN:first').addClass("choiceChoosed");
			} else {
				$(item).nextAll('.cTitle:first,.choiceSN:first').removeClass("choiceChoosed");
			}
		});
	}

	function _onReply(questionIndex) {
		var loc = "#question" + questionIndex;
		var cacheObj = $(loc);
		cacheObj.find(".userAnswer").attr("changed", "changed");
		var basicType = $(loc).attr("basicType");
		var replied = false;
		if (basicType == 1 || basicType == 3) {
			replied = true;
			// userAnswer
			// ;
			_changeChoiceColor(cacheObj);
		} else if (basicType == 2 || basicType == 10) {
			replied = $(loc).find("input:checkbox:checked").filter(".choice").size() > 0;
			// userAnswer
			var myanswer = 0;
			$(loc).find("input:checkbox:checked").filter(".choice").each(function(i, item) {
				myanswer += Math.pow(2, Number($(item).val()));
			});
			$(loc).find(".userAnswer").val(myanswer);

			_changeChoiceColor(cacheObj);
		} else if (basicType == 4) {
			_escapeXSS(loc);
			$(loc).find("input.blank").each(function(i, item) {
				if ($.trim($(item).val()) != '')
					replied = true;
			});
			// userAnswer
			var blankNum = $(loc).find("input.blank").size();
			var myanswer = [];
			$(loc).find("input.blank").each(function(i, item) {
				myanswer.push($.trim($(item).val()));
			});
			$(loc).find(".userAnswer").val(replied ? JSON.stringify(myanswer) : '');
		} else if (basicType == 5) {
			_escapeXSS(loc);
			replied = $.trim($(loc).find(".userAnswer").val()).length > 0;
			// userAnswer
			// ;
		} else if (basicType == 6) {
			replied = $.trim($(loc).find(".userAnswer").val()).length > 0;
			// userAnswer
			// ;
		}

		//alert(_getReply(questionIndex, ctrl));

		$('#jmp' + questionIndex).removeClass("saved");
		if (replied)
			$('#jmp' + questionIndex).addClass('replied');
		else
			$('#jmp' + questionIndex).removeClass('replied');

		_redrawPercent();
	}

	function _escapeXSS(loc) {
		$(loc).find("input.blank,textarea").each(function(i, item) {
			var v = $(item).val() + "";
			v = v.replace(/\"/img, "｀");
			v = v.replace(/\'/img, "｀");
			v = v.replace(/\</img, "〈");
			v = v.replace(/\>/img, "〉");
			v = v.replace(/\;/img, "；");
			v = v.replace(/script/img, "S_C_R_I_P_T");
			v = v.replace(/frame/img, "F_R_A_M_E");
			v = v.replace(/onclick/img, "O_N_C_L_I_C_K");
			v = v.replace(/onmove/img, "O_N_M_O_V_E");
			v = v.replace(/onerror/img, "O_N_E_R_R_O_R");
			v = v.replace(/alert/img, "A_L_E_R_T");
			v = v.replace(/confirm/img, "C_O_N_F_I_R_M");
			$(item).val(v);
		});
	}

	function _toggleFlag(questionIndex) {
		$('#jmp' + questionIndex).parent().toggleClass('flag');
	}

	function _redrawPercent() {
		if (jsExampro.totalQuestionNum > 0) {
			var num = $(".thumbnail").find(".saved,.replied").size();
			var percent = num * 1.0 / jsExampro.totalQuestionNum;
			if (num != jsExampro.totalQuestionNum && percent > 0.99) {
				percent = 0.99;
			}
			$("#percentBar").css("width", Math.round(percent * ($("#percentBar").parent().width() - 2)) + "px");
			var color = 'red';
			if (percent > 0.3) color = 'lightblue';
			if (percent > 0.7) color = 'lightgreen';
			$("#percentBar").css("background-color", color);
			$("#txtPercent").html(Math.round(percent * 100) + "%");
		}
	}

	function _reloadUserAnswer(questionId, reply, answerMs) {
		if (typeof(reply) == 'undefined') return;
		if (reply == '') return;

		var loc = ".question[questionId=" + questionId + "]:first";
		var cacheObj = $(loc);
		var questionIndex = cacheObj.attr("questionIndex");
		loc = "#question" + questionIndex;
		var basicType = cacheObj.attr("basicType");
		if (typeof(answerMs) != 'undefined')
			cacheObj.attr("answerMs", answerMs);
		if (basicType == 1 || basicType == 3) {
			cacheObj.find("input:radio.userAnswer[value=" + reply + "]").attr("checked", "checked");
		} else if (basicType == 2 || basicType == 10) {
			cacheObj.find("input.userAnswer").val(reply);
			cacheObj.find("input:checkbox").filter(".choice").each(function(i, item) {
				var x = Math.pow(2, Number($(item).val())) & Number(reply);
				if (x != 0) {
					$(item).attr("checked", "checked");
				}
			});
		} else if (basicType == 4) { // fill
			var ary = (reply instanceof Array) ? reply : eval("(" + reply + ")");
			cacheObj.find("input.blank").each(function(i, item) {
				$(item).val(ary[i]);
			});
			_onReply(questionIndex);
		} else if (basicType == 5) { // txt
			cacheObj.find("textarea.userAnswer").val(reply);
		} else if (basicType == 6) { // match
			cacheObj.find("input.userAnswer").val(typeof(reply) == 'string' ? reply : JSON.stringify(reply));
			jsMatchQuestion.reloadUserAnswer(questionIndex);
		}

		if (_isReplied(questionIndex)) {
			$('#jmp' + questionIndex).removeClass('replied').addClass("saved");
		}
		_changeChoiceColor(cacheObj);
		_redrawPercent();
	}

	function _getRepliedPercent() {
		if (jsExampro.totalQuestionNum <= 0) return 0;
		return Math.round($(".thumbnail").find(".saved,.replied").size() * 100.0 / jsExampro.totalQuestionNum);
	}

	// 重入考试时，装载历史作答
	function _loadReplies(callback) {
		$.ajax({
			dataType: "json",
			timeout: 60000,
			cache: false,
			url: jsExampro.basePath + jsExampro.urlLoadReplies,
			data: {
				resultId: jsExampro.resultId,
				r: Math.random()
			},
			success: function(data) {
				jsMsgbox.addMsg("请求历史作答成功");
				try {
					for (var i = 0; i < data.length; i++) {
						_reloadUserAnswer(data[i].q, data[i].r, data[i].t);
					}
					jsMsgbox.addMsg("恢复试卷作答数据完成");

					if (typeof(callback) != 'undefined') {
						eval(callback);
					}
				} catch (e) {
					jsMsgbox.addMsg("恢复试卷作答数据失败", e.message, "error");
				}
			},
			error: function(xhr, textStatus, errorThrown) {
				jsMsgbox.addMsg("恢复试卷作答数据失败[" + textStatus + "]", "", "error");
				jsMsgbox.addMsg(xhr.responseText, "", "detail");
				jsMsgbox.show();
			}
		});
	}

	function _clearLeftSeconds() {
		jsExampro.leftSeconds = 0;
	}

	function _preventReply(questionIndex) {
		if (typeof(questionIndex) == 'undefined') {
			$("#paperForm").find("input,textarea").attr("readonly", "readonly").css("background-color", "lightgray");
			$("#paperForm").find(":radio,:checkbox").hide();
			//$("#paperForm").find(":radio:checked,:checkbox:checked").next(".choiceSN").css("background-color", "#ff5a09");
			$("#paperForm").find(".choiceABC,.choice123").unbind().attr("onclick", "javascript:;");
			$("#paperForm").find(".tdLines a").hide();
		} else {
			var loc = "#question" + questionIndex;
			$("#paperForm").find(loc).find("input,textarea").attr("readonly", "readonly").css("background-color", "lightgray");
			$("#paperForm").find(loc).find(":radio,:checkbox").hide();
			$("#paperForm").find(loc).find(".choiceABC,.choice123").unbind().attr("onclick", "javascript:;");
			$("#paperForm").find(loc).find(".tdLines a").hide();
		}
	}

	function _help() {
		jsMsgbox.addMsg("考试过程中遇到疑难问题？<br />请联系管理员，并告知其帮助码" + jsExampro.helpCode, "", "important");
		jsMsgbox.show();
	}

	window.jsExampro = {
		basePath: '',
		urlAjaxSave: 'app/exampro/examreply/ExamReply/ajaxSave.do',
		urlLoadReplies: 'app/exampro/examreply/ExamReply/loadReplies.do',
		resultId: null,
		totalQuestionNum: 0,
		currentQuestionIndex: -1,
		leftSeconds: 999999999,
		leftEnterSeconds: 0,
		lastLeftSeconds: null, // 固定不变，直至下次服务器交互修正
		lastClientNow: null, // 固定不变，直至下次服务器交互修正
		countdownTimer: null, // 每秒倒计时
		replySaveTimer: null, // 定时自动保存
		forceGetPaper: 0, // 强制收卷1/0
		isPaperModeFull: _isPaperModeFull,
		isPaperModeSingle: _isPaperModeSingle,
		setPaperModeFull: _setPaperModeFull,
		setPaperModeSingle: _setPaperModeSingle,
		jumpTo: _jumpTo,
		jumpToPrev: _jumpToPrev,
		jumpToNext: _jumpToNext,
		countdown: _countdown,
		startSaveTimer: _startSaveTimer,
		replySave: _replySave,
		onReply: _onReply,
		prepareForSave: _prepareForSave,
		loadReplies: _loadReplies,
		autoSubmit: _autoSubmit,
		suspendReply: _suspendReply,
		forceGetPaper: _forceGetPaper,
		clearLeftSeconds: _clearLeftSeconds,
		toggleFlag: _toggleFlag,
		preventReply: _preventReply,
		debugNetwork: _debugNetwork,
		help: _help,
		reloadUserAnswer: _reloadUserAnswer,
		isReplied: _isReplied
	};
})();
// exam end

// common begin
(function() {
	function _disableContextmenu() {
		// $(document).bind("contextmenu", function(e) {
		// 	return false;
		// });
	}

	function _disableSelectstart() {
		// $(document).bind("selectstart", function(e) {
		// 	return false;
		// });
	}

	function _disableCopy() {
		// $(document).bind("copy", function(e) {
		// 	document.selection.empty();
		// 	return false;
		// });
		// $(document).bind("keydown", function(e) {
		// 	if (e.keyCode == 86 && e.ctrlKey) { //CTRL-V
		// 		return false;
		// 	} else if (e.keyCode == 123) {
		// 		return false; // F12
		// 	}
		// 	return true;
		// });
	}

	function _disablePaste() {
		// $(document).bind("paste", function(e) {
		// 	return false;
		// });
	}

	var _C = {};
	_C.disableContextmenu = _disableContextmenu;
	_C.disableSelectstart = _disableSelectstart;
	_C.disableCopy = _disableCopy;
	_C.disablePaste = _disablePaste;
	window.jsExamproCommon = _C;
})();
// common end

// msgbox begin
(function() {
	function _show() {
		if (!$("#msgbox").is(":visible")) {
			$("#msgbox").slideDown("slow");
			//$("#msgboxReshow").hide(); 
		}
		_scrollIt();
	}

	function _scrollIt() {
		if ($("#msgbox").is(":visible") && $("#msgbox").find("input.autoscroll").is(":checked")) {
			$("#msgbox .msg").animate({
				"scrollTop": $("#msgbox .msg")[0].scrollHeight
			}, 10); // 滚动条到最下面，让最新消息显示出来
		}
	}

	function _clearMsg(reservedNum) {
		var rownum = $("#msgbox .msg>table").find(".trmsg").size();
		if (rownum - reservedNum > 0) {
			$("#msgbox .msg>table").find(".trmsg:lt(" + (rownum - reservedNum) + ")").remove();
		}
	}

	function _addMsg(msg, advInfo, loglevel) {
		if ($("#msgbox .msg>table").size() == 0) {
			$("#msgbox .msg").html("<table width='100%'><tbody><tr class='trmsg'><td width='60%' class='important'>祝作答顺利！</td><td class='time'>" + (new Date()).toLocaleTimeString() + "</td><td class='adv'><textarea readonly></textarea></td></tr></tbody></table>");
		} else {
			_clearMsg(200);
		}

		$("#msgbox .msg>table").append("<tr class='trmsg'><td width='60%'></td><td class='time'></td><td class='adv'><textarea readonly></textarea></td></tr>");
		if (loglevel == 'detail') {
			$("#msgboxDetail").find("textarea").val(msg);
			$("#msgbox .msg>table").find(".trmsg:last").find("td:first")
				.html("<span style='cursor:pointer' onclick='$(\"#msgboxDetail\").show();jsExampro.debugNetwork();'>[查看诊断信息]</span>").addClass(loglevel);
		} else {
			$("#msgbox .msg>table").find(".trmsg:last").find("td:first").html(msg).addClass(typeof(loglevel) != 'undefined' ? loglevel : "");
		}
		$("#msgbox .msg>table").find(".trmsg:last").find("td.time").html((new Date()).toLocaleTimeString());
		if (typeof(advInfo) != 'undefined')
			$("#msgbox .msg>table").find(".trmsg:last").find("td.adv>textarea").val(advInfo);
		_scrollIt();
		_adv();
	}

	function _adv() {
		if ($("#msgbox").find("input:checkbox.adv").is(":checked")) {
			$("#msgbox").find("td.adv").show();
		} else {
			$("#msgbox td.adv").hide();
		}
	}

	var _x = {};
	_x.show = _show;
	_x.addMsg = _addMsg;
	_x.adv = _adv;
	window.jsMsgbox = _x;
})();
// msgbox end

// blockbox begin
(function() {
	function _msg(msg, msglevel) {
		_blockbox(msg, "", msglevel);
	}

	function _alert(msg, msglevel) {
		_blockbox(msg, "<input type='button' value='关闭' onclick='jsBlockbox.close()' />", msglevel);
	}

	function _blockbox(msg, buttons, msglevel) {
		msglevel = (typeof(msglevel) == 'undefined' || msglevel == null) ? 0 : Number(msglevel);
		if ($("#blockmsg").size() == 0 || $("#blockmsg").attr("msglevel") == jsBlockbox.VERYVERYLOW) {
			// 没有显示
			$.blockUI({
				message: "<div id='blockmsg' msglevel='" + msglevel + "'>" + msg + "</div><div id='blockbuttons'>" + buttons + "</div>"
			});
		} else {
			// 存在显示
			var currlevel = $("#blockmsg").attr("msglevel");
			if (currlevel <= Number(msglevel)) {
				$("#blockmsg").html(msg);
				$("#blockmsg").attr("msglevel", msglevel);
				$("#blockbuttons").html(buttons);
			} else {;
			}
		}
	}

	function _scrollIt() {
		$("#blockmsg").animate({
			"scrollTop": $("#blockmsg")[0].scrollHeight
		}, 0); // 滚动条到最下面，让最新消息显示出来
	}

	function _close() {
		$("#blockmsg").html("");
		$("#blockmsg").attr("msglevel", jsBlockbox.VERYVERYLOW);
		$.unblockUI();
	}

	var _x = {
		VERYVERYLOW: -20,
		VERYLOW: -10,
		LOW: -5,
		NORMAL: 0,
		HIGH: 5,
		VERYHIGH: 10
	};
	_x.msg = _msg;
	_x.alert = _alert;
	_x.blockbox = _blockbox;
	_x.close = _close;
	window.jsBlockbox = _x;
})();
// blockbox end

// matchquestion begin
(function() {
	function _clickPin(ctrl) {
		if ($(ctrl).is(".choosed")) {
			$(ctrl).removeClass("choosed");
			return;
		}
		var questionIndex = $(ctrl).parents(".match").attr("questionIndex");
		var loc = "#question" + questionIndex;
		var css = $(ctrl).is(".choice123") ? ".choice123" : ".choiceABC";
		$(loc).find(css + ".choosed").removeClass("choosed");
		$(ctrl).addClass("choosed");

		var pinABC = $(loc).find(".choiceABC.choosed");
		var pin123 = $(loc).find(".choice123.choosed");
		if (pinABC.size() != 1 || pin123.size() != 1)
			return;
		$(pinABC).removeClass("choosed");
		$(pin123).removeClass("choosed");
		var existed = $(loc).find("div[pinABC='" + $(pinABC).html() + "'][pin123='" + $(pin123).html() + "']").size() > 0;
		if (existed)
			return;
		$(loc).find(".tdLines").append("<div pinABC='" + $(pinABC).html() + "' pin123='" + $(pin123).html() + "'>匹配: " + $(pinABC).html() + " ~ " + $(pin123).html() + "<a href='javascript:;' onclick='jsMatchQuestion.removeLine(this)' >删除</a></div>");
		_updateUserAnswer(loc);
		jsExampro.onReply(questionIndex);
	}

	function _updateUserAnswer(loc) {
		var ary = [];
		$(loc).find(".tdLines div").each(function(i, item) {
			ary.push($(item).attr("pinABC") + "_" + $(item).attr("pin123"));
		});
		ary.sort();
		var str = JSON.stringify(ary);
		if (str == "[]") str = "";
		$(loc).find(".userAnswer").val(str);
	}

	function _removeLine(ctrl) {
		var questionIndex = $(ctrl).parents(".match").attr("questionIndex");
		var loc = "#question" + questionIndex;
		$(ctrl).parent().remove();
		_updateUserAnswer(loc);
		jsExampro.onReply(questionIndex);
	}

	function _reloadUserAnswer(questionIndex) {
		$(loc).find(".tdLines").html("");
		var loc = "#question" + questionIndex;
		var lines = $(loc).find(".userAnswer").val();
		if (lines == '') return;
		var lineAry = eval("(" + lines + ")");
		for (var i = 0; i < lineAry.length; i++) {
			var line = lineAry[i];
			$(loc).find(".tdLines").append("<div pinABC='" + line.charAt(0) + "' pin123='" + line.charAt(2) + "'>匹配: " + line.charAt(0) + " ~ " + line.charAt(2) + "<a href='javascript:;' onclick='jsMatchQuestion.removeLine(this)' >删除</a></div>");
		}
	}

	var _x = {
		clickPin: _clickPin,
		removeLine: _removeLine,
		reloadUserAnswer: _reloadUserAnswer
	};
	window.jsMatchQuestion = _x;
})();
// matchquestion end

// media begin
(function() {
	function _play(questionId) {
		var loc = "tr[questionId=" + questionId + "]";
		$(loc).find("input[playedCount]").attr("disabled", "disabled");
		var playedCount = Number($(loc).find("input[playedCount]").attr("playedCount")) + 1;
		$(loc).find("input[playedCount]").attr("playedCount", playedCount);
		_setControl(questionId);
		document.getElementById("media" + questionId).play();
	}

	function _leftPlayCount(questionId) {
		var loc = "tr[questionId=" + questionId + "]";
		var playedCount = $(loc).find("input[playedCount]").attr("playedCount");
		var maxPlayCount = $(loc).find("input[playedCount]").attr("maxPlayCount");
		return Number(maxPlayCount) - Number(playedCount);
	}

	function _setControl(questionId) {
		var loc = "tr[questionId=" + questionId + "]";
		$(loc).find("input[playedCount]").val("播放音频文件（剩余播放次数" + _leftPlayCount(questionId) + "）");
	}

	function _buildMediaPlay(path) {
		$("tr[mediaPlayCount]").each(function(i, item) {
			var questionId = $(item).attr("questionId");
			var mediaFilePath = path + $(item).attr("mediaFilePath");
			if (true) {
				var x = $(item).hasClass("complex") ? "br:first" : "span.score";
				$(item).find("td:first").find(x).before("<input style='margin:0px 10px;' type='button' playedCount='0' maxPlayCount='" + $(item).attr("mediaPlayCount") + "' onclick='jsExamMedia.play(" + questionId + ")' /><audio id='media" + questionId + "' class='qm'>您的浏览器不支持 audio 标签</audio>");
				$("#media" + questionId).attr("src", mediaFilePath);
				$("#media" + questionId).bind("ended", function() {
					if (_leftPlayCount(questionId) > 0)
						$("tr[questionId=" + questionId + "]").find("input[playedCount]").removeAttr("disabled");
				});
				_setControl(questionId);
			}
		});
	}

	var _x = {
		play: _play,
		buildMediaPlay: _buildMediaPlay
	};
	window.jsExamMedia = _x;
})();
// media end